package py.com.fms.fms.session.maintenances;

//External classes imports 
//Java Classes
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.faces.convert.ConverterException;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports

import py.com.fms.fms.bean.RefDetBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.bean.RolesBean;
import py.com.fms.fms.bean.UsersRolesBean;


import py.com.fms.fms.persistence.services.RefServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.fms.persistence.services.RolesServices;
import py.com.fms.fms.persistence.services.UsersRolesServices;

import py.com.fms.exception.CommonException;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;

import py.com.fms.utilities.*;

@SuppressWarnings("unused")
@Name("editUserRole")
@Scope(ScopeType.SESSION)
public class EditUserRole {
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	
	private DateAssistant dateAssist;

	// Attribute used for saving and deleting
	private UsersRolesBean userRole;
	private UsersRolesBean userRoleToDelete;
	
	// Services
	private UsersRolesServices urSrv;
	private UsersServices usSrv;
	private RolesServices rlSrv;
	
	// Collection of monedasBean
	private Collection<UsersRolesBean> allUsersRoles;
	private Collection<UsersRolesBean> usersRolesList;

	// Attribute used for editing or updating
	private UsersRolesBean editUserRole;
	
//	Necessary Attributes;
	private Boolean checkDet = new Boolean(false);
	
	

	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.initBeans();
			this.initUsersRoless();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();

		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	public void initBeans(){
		
		if (userRole == null){
			userRole = new UsersRolesBean();
			userRole.setStatus(true);
		}
		
		if (userRoleToDelete == null){
			userRoleToDelete = new UsersRolesBean();
		}
		
		if (editUserRole == null){
			editUserRole = new UsersRolesBean();
		}
	}
	
	public void initUsersRoless() throws CommonException{
		
		if (urSrv == null){
			urSrv = new UsersRolesServices(this.sqlMap.getConfig());
		}
		
		if (usSrv == null){
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		
		if (rlSrv == null){
			rlSrv = new RolesServices(this.sqlMap.getConfig());
		}
		
				
	}
	
	public void initAssistants(){
		
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
		
	}
	
	public void initCollections(){
		if(allUsersRoles == null){
			allUsersRoles = new ArrayList<UsersRolesBean>();
		}
		
		if(usersRolesList == null){
			usersRolesList = new ArrayList<UsersRolesBean>();
		}
		
	

	}
	
	public void cleanData(){
		
		// Cleaning Beans
		userRole = null;
		userRoleToDelete = null;
		editUserRole = null;
		
		// Cleaning Services
		urSrv = null;
		usSrv = null;
		rlSrv = null;
		
		// Cleaning Assistants
		aid = null;
		convert = null;
		dateAssist = null;

		// Cleaning Collections
		allUsersRoles = null;
		usersRolesList = null;
	
	}

	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			this.setAllUsersRoles(urSrv.getAllUsersRoles());
			for (UsersRolesBean userRole : this.getAllUsersRoles()) {
				System.out.println(userRole.getId());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public void cancelData() throws CommonException {
//		this.facesMessages.clear();
		this.setInitVar("S");
		this.cleanData();
		this.initData();
	}
	
	public void addUsersRolesList(){
		
		try{
			System.out.println("Filling Detail list");
			if (this.getUserRole() == null){
				System.out.println("Entity null");
			}else{
		
				usersRolesList.add(this.getUserRole());
				
				System.out.println("User: " + this.getUserRole().getUserData().getUserName());
				System.out.println("Role: " + this.getUserRole().getRoleData().getDescrip());
				System.out.println(this.getUsersRolesList());
				System.out.println("------------------------");
				System.out.println("                        ");
				System.out.println("------------------------");
				
				UsersBean user = this.getUserRole().getUserData();
				this.setCheckDet(false);
				this.setUserRole(null);
				this.setInitVar("S");
				this.initData();
				this.getUserRole().setUserData(user);

			}
			
		}catch(Exception e){
			this.log.error(e);
			
		}
	
	}
	
	public void detToDelete(UsersRolesBean bean){
		System.out.println("Delete Details executed");
		System.out.println("Remove: " + this.getUserRoleToDelete() + " = " + bean);
		System.out.println("Check: " + this.getCheckDet());
//		if(checkDet == true){
//			bean.setSelected(true);
//		}else{
//			if(checkDet == false){
//				bean.setSelected(false);
//			}
//			
//		}
		
		System.out.println("Remove Object:" + bean);
		System.out.println("Selected:" + bean.getSelected());
		System.out.println("[[--------------------]]");
		System.out.println("  ||||||||||||||||||||  ");
		System.out.println("[[--------------------]]");
		
	}
	
	public void deleteDet(){
		int i;	
		if (usersRolesList.isEmpty()) {
			System.out.println("Empty List");
		}else{
			
			System.out.println("Elimination Method executed");
			System.out.println("Detail List: " + this.getUsersRolesList());
			
			Iterator<UsersRolesBean> it = usersRolesList.iterator();
			
			while(it.hasNext()){
				UsersRolesBean next = it.next();
				System.out.println("Next: " + next);
				System.out.println("Next: " + next.getSelected());
				if(next.getSelected() == true){
					System.out.println("Next: " + next.getSelected());
					it.remove();
				}
			}
			
			
			System.out.println("Elements eliminated");
			System.out.println("Details: " + this.getUsersRolesList());
			System.out.println("------------------------");
											
			
		}
		this.setInitVar(null);
		this.checkDet = false;
		

	}
		

	// Used for data saving process
	public void saveNewData() throws ParseException {
		try {
//			this.facesMessages.clear();
			UsersRolesBean newUserRole = new UsersRolesBean();
			Long user = new Long(1);
			aid = new WithinHolder();
			this.today = DateAssistant.getHoleDateTime();
			
			if (this.getUserRole() == null) {
				System.out.println("UsersRoles Entity == null");
				throw new CommonException("UsersRoles Entity is null");
			}
			
			System.out.println("BEFORE SETTING VALUES");
			
			// Defining an iterator
			
			Iterator<UsersRolesBean> it = usersRolesList.iterator();
			
			// Setting field values
			while(it.hasNext()){
				
				UsersRolesBean next = it.next();
				
				newUserRole.setIdRole(next.getRoleData().getId());
				newUserRole.setIdUser(next.getUserData().getId());
				newUserRole.setStartDate(this.today);
				newUserRole.setLastUpdDate(this.today);
				newUserRole.setStatus(next.getStatus());
				newUserRole.setUserIns(user);
				
				urSrv.saveNewUsersRoles(newUserRole);
				
			}
			
			// Cleaning field values
			newUserRole = null;
			
			// Setting Initialization VAR
			this.setInitVar("S");
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}finally{
			this.cleanData();
		}
	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id) throws CommonException{
		System.out.println("id = " + id.toString());
		for (UsersRolesBean bean : this.getAllUsersRoles()) {
			if(bean.getId() == id){
				this.setEditUserRole(bean);
				return;
			}			
		}	
	}
	
	public void dataToEditUpd() throws ParseException{
		try {
			// SETTING EXTERNAL VALUES
			this.today = DateAssistant.getHoleDateTime();

			
			// UPDATING EXTERNAL VALUES
			this.getEditUserRole().setLastUpdDate(this.today);
			
			// SAVING VALUES
			urSrv.updateUsersRoles(this.getEditUserRole());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void dataToDelete(Long id){
		for (UsersRolesBean bean: this.getAllUsersRoles()){
			if (bean.getId() == id) {
				try {
					urSrv.deleteUsersRolesById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}
	
	
	// GETTERS AND SETTERS
	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public UsersRolesBean getUserRole() {
		return userRole;
	}

	public void setUserRole(UsersRolesBean userRole) {
		this.userRole = userRole;
	}

	public UsersRolesBean getUserRoleToDelete() {
		return userRoleToDelete;
	}

	public void setUserRoleToDelete(UsersRolesBean userRoleToDelete) {
		this.userRoleToDelete = userRoleToDelete;
	}

	public Collection<UsersRolesBean> getAllUsersRoles() {
		return allUsersRoles;
	}

	public void setAllUsersRoles(Collection<UsersRolesBean> allUsersRoles) {
		this.allUsersRoles = allUsersRoles;
	}

	public Collection<UsersRolesBean> getUsersRolesList() {
		return usersRolesList;
	}

	public void setUsersRolesList(Collection<UsersRolesBean> usersRolesList) {
		this.usersRolesList = usersRolesList;
	}

	public UsersRolesBean getEditUserRole() {
		return editUserRole;
	}

	public void setEditUserRole(UsersRolesBean editUserRole) {
		this.editUserRole = editUserRole;
	}

	public Boolean getCheckDet() {
		return checkDet;
	}

	public void setCheckDet(Boolean checkDet) {
		this.checkDet = checkDet;
	}
	
	
	
}
